package com.bai.websocketandmybatisplus.web.websocket;

import com.bai.websocketandmybatisplus.exception.AllErrorEnum;
import com.bai.websocketandmybatisplus.exception.MyException;
import com.bai.websocketandmybatisplus.mapper.ChatHistoryMapper;
import com.bai.websocketandmybatisplus.model.ChatHistory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.time.LocalDateTime;

// 添加 @Component 注解以确保 ChatEndpoint 被 Spring 正确扫描
@Component
@ServerEndpoint(value = "/chat")
public class ChatEndpoint implements ApplicationContextAware { // ApplicationContextAware 用于让Bean获取到Spring容器的上下文。
    @Autowired
    private static ChatHistoryMapper chatHistoryMapper;


    @OnOpen
    public void onOpen(Session session) {
        System.out.println("连接建立: " + session.getId());
    }

    @OnMessage
    public void onMessage(String content, Session session) {
        // 插入消息到数据库
        ChatHistory chatHistory = new ChatHistory();
        chatHistory.setContent(content);
        chatHistory.setCreatedAt(LocalDateTime.now());

        try {
            chatHistoryMapper.insert(chatHistory);
        } catch (Exception e) {
            throw new MyException(AllErrorEnum.CHAT_INSERT_ERROR);
        }

        // 获取当前端点上所有活跃的会话。并用增强for循环
        for (Session session1 : session.getOpenSessions()) {
            if (session1.isOpen()) {
                try {
                    session1.getBasicRemote().sendText(content);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    @OnClose
    public void onClose(Session session) {
        System.out.println("连接关闭: " + session.getId());
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        System.out.println("发生错误: " + session.getId());
        throwable.printStackTrace();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        chatHistoryMapper = applicationContext.getBean(ChatHistoryMapper.class);
    }
}